package com.app.island.cash.acts

import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.DataBindingUtil
import com.app.island.cash.R
import com.app.island.cash.databinding.ActivityFeedbackLayoutBinding
import com.app.island.cash.data.sigle.FeedDataCall
import com.app.island.cash.params.AppParams
import com.app.island.cash.requestwork.*
import com.app.island.cash.utilstools.NetWorkLoadingUtil
import com.app.island.cash.utilstools.SystemUtils
import com.app.island.cash.utilstools.ToastUtil
import com.app.island.cash.utilstools.UserInfoManager
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.lang.reflect.InvocationTargetException
import java.net.URLDecoder
import java.util.*

class FeedbackActivity :BaseAct() {

    private lateinit var binding: ActivityFeedbackLayoutBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=DataBindingUtil.setContentView(this,R.layout.activity_feedback_layout)
        binding.tvPageTitle.text="Feedback"
        binding.ivFinish.setOnClickListener { finish() }
        binding.submitContent.setOnClickListener {
            feedbackData()
        }
    }
    private fun dynamicParams(map: TreeMap<String, Any>): TreeMap<String, Any> {
        map["mobileType"] = "2"
        map["versionNumber"] = SystemUtils.versionCode
        map["appFlag"] = AppParams.flag
        map["channelCode"] = AppParams.channel
        val token = UserInfoManager.instance.token!!
        val userId = UserInfoManager.instance.uid
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(userId)) {
            map["token"] = token
            map["userId"] = userId
        }
        return map
    }

    private fun feedbackData() {
        val data = binding.inputFeedback.text.toString()
        if (TextUtils.isEmpty(data)) {
            ToastUtil.toast("please enter feedback please")
            return
        }
        val call = FeedDataCall()
        call.opinion = data
        val map: Map<String, Any> = getFieldVlaue(call)
        var tree: TreeMap<String, Any> = TreeMap(map)
        tree = dynamicParams(tree)
        val temp: TreeMap<*, *> = TreeMap<Any?, Any?>(tree)
        val head: MutableMap<String, String> = HashMap()
        head["token"] = UserInfoManager.instance.token
        head["signMsg"] = getSign(temp)
        NetWorkLoadingUtil.showDialog(this)
        NetImageClient.getService(
            AppService::class.java
        ).updateFeedback(head, getRequestMap(tree)).enqueue(object : RequestCallBack<HttpResult<Any>?>() {
            override fun onSuccess(body: HttpResult<Any>?) {
                ToastUtil.toast(body?.msg)
                finish()
            }
        })
    }

    private fun getFieldVlaue(obj: Any): Map<String, Any> {
        val mapValue: MutableMap<String, Any> = HashMap()
        val cls: Class<*> = obj.javaClass
        val fields = cls.declaredFields
        try {
            for (field in fields) {
                val name = field.name
                val strGet =
                    "get" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length)
                val methodGet = cls.getDeclaredMethod(strGet)
                val `object` = methodGet.invoke(obj)
                val value = `object` ?: ""
                mapValue[name] = value
            }
        } catch (e: NoSuchMethodException) {
            e.printStackTrace()
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
        return mapValue
    }

    private fun getSign(map: TreeMap<*, *>): String {
        var signa = ""
        try {
            val it: Iterator<*> = map.entries.iterator()
            val sb = StringBuilder()
            while (it.hasNext()) {
                val entry = it.next() as Map.Entry<*, *>
                if (entry.value is File) continue  //URLEncoder.encode(, "UTF-8")
                sb.append(entry.key).append("=")
                    .append(URLDecoder.decode(entry.value.toString(), "UTF-8")).append("|")
            }
            // 所有请求参数排序后的字符串后进行MD5（32）
            //signa = MDUtil.encode(MDUtil.TYPE.MD5, sb.toString());
            // 得到的MD5串拼接appsecret再次MD5，所得结果转大写
            var sign = ""
            sign = if (sb.toString().length > 1) {
                sb.toString().substring(0, sb.length - 1)
            } else {
                sb.toString()
            }
            signa = SystemUtils.encode(AppParams.SIGN_KEY + UserInfoManager.instance.token + sign)!!
                .toUpperCase()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return signa
    }

    companion object {
        fun getRequestMap(map: Map<String, Any>): Map<String, RequestBody> {
            val params: MutableMap<String, RequestBody> = HashMap()
            for ((key, value) in map) {
                if (TextUtils.isEmpty(key) || null == value) {
                    continue
                }
                if (value is File) {
                    val file = value
                    params[key.toString() + "\"; filename=\"" + file.name + ""] =
                        RequestBody.create(MultipartBody.FORM, file)
                } else {
                    params[key as String] =
                        RequestBody.create(MultipartBody.FORM, (value as String?)!!)
                }
            }
            return params
        }

    }
}